#!/bin/sh
share_path="/home/SMB"
password=""
# 检查用户是否为root
rootness(){
	if [[ $EUID -ne 0 ]]; then
	   echo "错误：此脚本必须以超级用户身份运行!" 1>&2
	   exit 1
	fi
}

rand(){
	index=0
	str=""
	for i in {a..z}; do arr[index]=${i}; index=`expr ${index} + 1`; done
	for i in {A..Z}; do arr[index]=${i}; index=`expr ${index} + 1`; done
	for i in {0..9}; do arr[index]=${i}; index=`expr ${index} + 1`; done
	for i in {1..10}; do str="$str${arr[$RANDOM%$index]}"; done
	echo ${str}
}

get_char(){
	SAVEDSTTY=`stty -g`
	stty -echo
	stty cbreak
	dd if=/dev/tty bs=1 count=1 2> /dev/null
	stty -raw
	stty echo
	stty $SAVEDSTTY
}

preinstall_samba(){
	# echo "请输入共享文件夹:"
	# read -p "(默认目录: /home/SMB):" share_path
	# [ -z ${share_path} ] && share_path="/home/SMB"

	password=`rand`
	echo "请输入共享密码:"
	read -p "(默认密码: ${password}):" tmppassword
	[ ! -z ${tmppassword} ] && password=${tmppassword}

	echo
	echo "Samba帐户:smbroot"
	echo "密码:${password}"
	echo
	echo "按任意键开始... 或按Ctrl C取消."
	char=`get_char`
}

install_samba(){
	setenforce 0
	sed -i 's/enforcing/disabled/g' /etc/selinux/config
	rmdir ${share_path} 1>/dev/null 2>&1
	if [ -d ${share_path} ]; then
		echo "该目录已经存在: ${share_path}"
		echo "退出"
		exit 1
	fi
	echo "安装samba..."
	yum install -y samba
	config_samba
}

config_samba(){
	groupadd sambagp
	useradd smbroot -g sambagp -s /sbin/nologin -M # samba manager

	mkdir -p ${share_path}
	chown smbroot:sambagp ${share_path}
	echo -e "${password}\n${password}" | smbpasswd -a smbroot 1>/dev/null 2>&1

	echo "更改Samba配置..."

	cp /etc/samba/smb.conf /etc/samba/smb.conf.bak  # backup samba conf

	cat > /etc/samba/smb.conf <<EOF
[global]

# ----------------------- Network-Related Options -------------------------
#
	workgroup = WORKGROUP
	server string = Samba Server Version %v
	netbios name = LINUXSERVER

;	interfaces = lo eth0 192.168.12.2/24 192.168.13.2/24
;	hosts allow = 127. 192.168.12. 192.168.13.
        map to guest = Bad User
        lanman auth = no
        ntlm = no
# --------------------------- Logging Options -----------------------------
#
# log file = specify where log files are written to and how they are split.
#
# max log size = specify the maximum size log files are allowed to reach. Log
# files are rotated when they reach the size specified with "max log size".
#

	# log files split per-machine:
	log file = /var/log/samba/log.%m
	# maximum size of 50KB per log file, then rotate:
	max log size = 50

# ----------------------- Standalone Server Options ------------------------
#
# security = the mode Samba runs in. This can be set to user, share
# (deprecated), or server (deprecated).
#
# passdb backend = the backend used to store user information in. New
# installations should use either tdbsam or ldapsam. No additional configuration
# is required for tdbsam. The "smbpasswd" utility is available for backwards
# compatibility.
#

	security = user
	passdb backend = tdbsam


#----------------------------- Name Resolution -------------------------------
#
# This section details the support for the Windows Internet Name Service (WINS).
#
# Note: Samba can be either a WINS server or a WINS client, but not both.
#
# wins support = when set to yes, the NMBD component of Samba enables its WINS
# server.
#
# wins server = tells the NMBD component of Samba to be a WINS client.
#
# wins proxy = when set to yes, Samba answers name resolution queries on behalf
# of a non WINS capable client. For this to work, there must be at least one
# WINS server on the network. The default is no.
#
# dns proxy = when set to yes, Samba attempts to resolve NetBIOS names via DNS
# nslookups.

	wins support = yes
;	wins server = w.x.y.z
;	wins proxy = yes

;	dns proxy = yes

# --------------------------- Printing Options -----------------------------
#
# The options in this section allow you to configure a non-default printing
# system.
#
# load printers = when set you yes, the list of printers is automatically
# loaded, rather than setting them up individually.
#
# cups options = allows you to pass options to the CUPS library. Setting this
# option to raw, for example, allows you to use drivers on your Windows clients.
#
# printcap name = used to specify an alternative printcap file.
#

	load printers = yes
	cups options = raw

;	printcap name = /etc/printcap
	# obtain a list of printers automatically on UNIX System V systems:
;	printcap name = lpstat
;	printing = cups


#============================ Share Definitions ==============================

[homes]
	comment = Home Directories
	browseable = no
	writable = yes
;	valid users = %S
;	valid users = MYDOMAIN\%S

[printers]
	comment = All Printers
	path = /var/spool/samba
	browseable = no
	guest ok = no
	writable = no
	printable = yes


# A publicly accessible directory that is read only, except for users in the
# [share]
# 	comment = Share
# 	path = /home/SMB
# 	public = yes
# 	available = yes
# 	admin users = smbroot
# 	valid users = @sambagp
# 	writable = yes
# 	write list = @sambagp
# 	create mask= 0755
# 	directory mask= 0755
# 	browseable = yes
EOF
}

finally(){
	systemctl enable smb.service
	systemctl start smb.service
	systemctl enable nmb.service
	systemctl start nmb.service

	echo
	echo "###############################################################"
	echo "# Samba服务器安装程序                                           #"
	echo "# 系统支持: CentOS 7+ / Redhat 7+                              #"
	echo "# 简介：samba服务器自动安装和设置脚本                              #"
	echo "###############################################################"
	echo "安装完成!"
	echo "好好享受!!(^з^)-☆"
	echo
	echo "sambaroot : smbroot"
	echo "Password : ${password}"
	echo
	echo "如果要修改用户设置，请使用以下命令:"
	echo "samba_setup -a (新增用户)"
	echo "samba_setup -d (删除用户)"
	echo "samba_setup -l (列出所有用户)"
	echo "samba_setup -m (修改用户密码)"
	echo
	echo
}

smb(){
	clear
	echo
	echo "###############################################################"
	echo "# Samba服务器安装程序                                           #"
	echo "# 系统支持: CentOS 7+ / Redhat 7+                              #"
	echo "# 简介：samba服务器自动安装和设置脚本                              #"
	echo "###############################################################"
	echo
	rootness
	preinstall_samba
	install_samba
	finally
}

add_conf(){
	user=$1
	grep -w "\[${user}\]" /etc/samba/smb.conf 1>/dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo "配置已经存在!"
		exit 1
	fi
	cat >> /etc/samba/smb.conf <<EOF
[${user}]
	comment = ${user}
	path = ${share_path}/${user}
	public = no
	available = yes
	admin users = smbroot
	writable = yes
	read list = 
	write list = smbroot ${user}
	valid users = smbroot ${user}
	create mask= 0755
	directory mask= 0755
	browseable = yes
#end[${user}]
EOF
}
add_folder(){
	folder=$1
	ls ${share_path} | grep -w "\[${folder}\]"  1>/dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo "文件夹已经存在!"
		exit 1
	fi
	mkdir -p ${share_path}/${folder}
	#chown ${user}:sambagp ${share_path}/${user}
	cat >> /etc/samba/smb.conf <<EOF
[${folder}]
	comment = ${folder}
	path = ${share_path}/${folder}
	public = no
	available = yes
	admin users = smbroot
	writable = yes
	read list = 
	write list = smbroot 
	valid users = smbroot 
	create mask= 0755
	directory mask= 0755
	browseable = yes
#end[${folder}]
EOF
	echo "创建文件夹完成."
}

del_folder(){
	folder=$1
	rmdir ${share_path}/${folder}
	sed -i "/\[${folder}\]/,/#end\[${folder}\]/"d /etc/samba/smb.conf
	systemctl reload smb
	echo "文件夹 (${folder}) 删除成功."
}

add_p(){
	user=$1
	folder=$2
	rw=$3
	if [ "${rw}" != "read" ] && [ "${rw}" != "write" ]; then
		echo "特权 (${rw}) 错误"
		exit 1
	fi
	pdbedit -L | grep -w "${user}" > /dev/null 2>&1
	#if not found
	if [ ! $? -eq 0 ];then
		echo "用户名 (${user}) 不存在. 请重新输入用户名."
		exit 1
	fi
	cat /etc/samba/smb.conf | grep -w "\[${folder}\]" > /dev/null 2>&1
	if [ ! $? -eq 0 ];then
		echo "文件夹 (${folder}) 不存在. 请重新输入名称."
		exit 1
	fi
	# get user from write|read list
	sed -n "/\[${folder}\]/,/#end\[${folder}\]/"p /etc/samba/smb.conf | grep -w "${rw} list.*${user}" > /dev/null 2>&1
	# not found
	if [ ! $? -eq 0 ];then
		# add user to write|read list
		sed -i "/\[${folder}\]/,/#end\[${folder}\]/s/${rw} list.*/& ${user}/g" /etc/samba/smb.conf
	fi
	# get user from valid user
	sed -n  "/\[${folder}\]/,/\#end\[${folder}\]/"p /etc/samba/smb.conf | grep -w  "valid.*${user}"  > /dev/null 2>&1
	# not found
	if [ ! $? -eq 0 ];then
		# add user to valid user
		sed -i "/\[${folder}\]/,/#end\[${folder}\]/s/\tvalid.*/& ${user}/g" /etc/samba/smb.conf
	fi
	echo "更改特权已完成."
}

del_p(){
	user=$1
	folder=$2
	rw=$3
	if [ "${rw}" != "read" ] && [ "${rw}" != "write" ]; then
		echo "权限 (${rw}) 错误"
		exit 1
	fi
	pdbedit -L | grep -w "${user}" > /dev/null 2>&1
	if [ ! $? -eq 0 ];then
		echo "用户名 (${user}) 不存在. 请重新输入用户名."
		exit 1
	fi
	cat /etc/samba/smb.conf | grep -w "\[${folder}\]" > /dev/null 2>&1
	if [ ! $? -eq 0 ];then
		echo "文件夹 (${folder}) 不存在. 请重新输入名称."
		exit 1
	fi
	# delete user from write|read list
	sed -i "/\[${folder}\]/,/#end\[${folder}\]/s/\(\t${rw} list.*\) ${user}\(.*\)/\1\2/g" /etc/samba/smb.conf
	# get user in write or read list
	sed -n  "/\[${folder}\]/,/\#end\[${folder}\]/"p /etc/samba/smb.conf | grep -w  "list.*${user}"  > /dev/null 2>&1
	# not in any list
	if [ ! $? -eq 0 ];then
		# delete user from valid user
		sed -i "/\[${folder}\]/,/#end\[${folder}\]/s/\(\tvalid.*\) ${user}\(.*\)/\1\2/g" /etc/samba/smb.conf
	fi
	echo "更改权限完成."
}

add_user(){
	rootness
	user=$1
	pass=$2
	if [ -z "${user}" ] || [ -z "${pass}" ]; then
		while :
		do
			read -p "请输入用户名:" user
			if [ -z ${user} ]; then
				echo "用户名不能为空"
			else
				pdbedit -L | grep -w "${user}" > /dev/null 2>&1
				if [ $? -eq 0 ];then
					echo "用户名 (${user}) 已经存在. 请重新输入用户名."
				else
					break
				fi
			fi
		done
		pass=`rand`
		echo "请输入 ${user}的密码:"
		read -p "(默认密码: ${pass}):" tmppass
		[ ! -z ${tmppass} ] && pass=${tmppass}
	fi
	pdbedit -L | grep -w "${user}" > /dev/null 2>&1
	if [ $? -eq 0 ];then
		echo "用户名 (${user}) 已经存在. 请重新输入用户名."
		exit 1
	fi
	useradd ${user} -g sambagp -s /sbin/nologin -M
	echo -e "${pass}\n${pass}" | smbpasswd -a ${user} 1>/dev/null 2>&1

	mkdir -p ${share_path}/${user}
	chown ${user}:sambagp ${share_path}/${user}

	add_conf ${user}
	systemctl reload smb
	echo "用户 (${user}) 添加完成."
}

list_users(){
	pdbedit -L
}

del_user(){
	rootness
	user=$1
	if [ -z "${user}" ]; then
		while :
		do
			read -p "请输入用户名:" user
			if [ -z ${user} ]; then
				echo "用户名不能为空"
			else
				break
			fi
		done
	fi
	rmdir ${share_path}/${user}
	sed -i "/\[${user}\]/,/#end\[${user}\]/"d /etc/samba/smb.conf
	smbpasswd -x ${user}
	userdel ${user}
	systemctl reload smb
	echo "用户 (${user}) 删除成功."
}

mod_user(){
	rootness
	user=$1
	pass=$2
	if [ -z "${user}" ] || [ -z "${pass}" ]; then
		while :
		do
			read -p "请输入用户名:" user
			if [ -z ${user} ]; then
				echo "用户名不能为空"
			else
				pdbedit -L | grep -w "${user}" > /dev/null 2>&1
				if [ $? -eq 0 ];then
					break
				else
					echo "用户 (${user}) 不存在. 请重新输入用户名."
				fi
			fi
		done
		pass=`rand`
		echo "请输入 ${user}的密码:"
		read -p "(默认密码: ${pass}):" tmppass
		[ ! -z ${tmppass} ] && pass=${tmppass}
	fi
	pdbedit -L | grep -w "${user}" > /dev/null 2>&1
	if [ ! $? -eq 0 ];then
		echo "用户 (${user}) 不存在. 请重新输入用户名."
		exit 1
	fi
	# useradd ${user} -g sambagp -s /sbin/nologin -M
	echo -e "${pass}\n${pass}" | smbpasswd -a ${user} 1>/dev/null 2>&1
	systemctl reload smb
	echo "用户 (${user}) 修改成功."
}

# Main process
action=$1
if [ -z ${action} ] && [ "`basename $0`" != "samba_setup" ]; then
	action=install
fi

case ${action} in
	install)
		smb
		;;
	-l|--list)
		list_users
		;;
	-a|--add)
		add_user $2 $3
		;;
	-d|--del)
		del_user $2
		;;
	-m|--mod)
		mod_user $2 $3
		;;
	-p|--privilage)
		add_p $2 $3 $4
		;;
	-u|--unprivilage)
		del_p $2 $3 $4
		;;
	-f|--folder)
		add_folder $2
		;;
	-g|--delfolder)
		del_folder $2
		;;
	-h|--help)
		echo "用法:   `basename $0` -l,--list                列出所有用户"
		echo "       `basename $0` -a,--add <user> <pass>   添加用户"
		echo "       `basename $0` -d,--del <user>          删除用户"
		echo "       `basename $0` -m,--mod <user> <pass>   修改用户密码"
		echo "       `basename $0` -p,--privilage <user> <foler> {read|write}   添加用户权限"
		echo "       `basename $0` -u,--unprivilage <user> <foler> {read|write}   移除用户权限"
		echo "       `basename $0` -f,--folder <foler>   创建一个文件夹"
		echo "       `basename $0` -g,--delfolder <foler>   删除一个文件夹"
		echo "       `basename $0` -h,--help                打印此帮助信息"
		;;
	*)
		echo "用法: `basename $0` [-l,--list|-a,--add|-d,--del|-m,--mod|-p,--privilage|-u,--unprivilage|-f,--folder|-g,--delfolder|-h,--help]" && exit
		;;
esac
